//
//  PieView.swift
//  MMTest
//
//  Created by liujianlong on 2022/10/21.
//

import UIKit


class PieView: UIView {
    @IBOutlet var cycle: UIView!
    @IBOutlet var leftPercent: UILabel!
    @IBOutlet var rightPercent: UILabel!
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        self.loadView()
    }
   
    
    var percents = [Int](){
        didSet{
            let hex0 = percents[0] < 65 ? "#FFFFFF":"#FA2C2C"
            let hex1 = percents[1] < 65 ? "#FFFFFF":"#FA2C2C"
            let hex2 = percents[0] + percents[1] == 0 ? "#FFFFFF":"#FFDD44"
            self.leftPercent.isHidden = percents[0] <= 0
            self.rightPercent.isHidden = percents[1] <= 0
            self.leftPercent.attributedText = RecordView.attr("\(percents[0])","%",hex0,hex0)
            self.rightPercent.attributedText = RecordView.attr("\(percents[1])","%",hex1,hex1)
            self.bglayer.strokeEnd = percents[0] + percents[1] == 0 ? 0 : 1
            self.cyclelayer.strokeEnd = CGFloat(CGFloat(percents[1]) / 100)
            self.cycle.cornerRadius = self.cycle.bounds.size.width / 2
            self.cycle.shadow("#999999".color(), CGSize(width:2, height:2), 6, self.cycle.bounds.width / 2)
            self.cycle.bgHexColor = hex2
        }
    }
    
    
    lazy var cyclelayer:CAShapeLayer = {
        let layer = self.getlayer("#2D85FF".color())
        self.cycle.layer.addSublayer(layer)
        return layer
    }()
    lazy var bglayer:CAShapeLayer = {
        let layer = self.getlayer("#FFDD44".color())
        self.cycle.layer.addSublayer(layer)
        return layer
    }()
    func getlayer(_ color:UIColor)->CAShapeLayer{
        let r = self.cycle.bounds.width / 2
        let bounds = CGRect(x:0, y:0, width: 2 * r, height: 2 * r)
        print(" self22222222   2\(self)  \n \(self.cycle)")

        let layer = CAShapeLayer()
        let path = UIBezierPath(arcCenter: CGPoint(x:r, y: r), radius: r, startAngle: Double.pi*3/2, endAngle: Double.pi*7/2, clockwise: true)
        layer.frame = self.cycle.bounds
        layer.lineWidth =  2 * r
        layer.fillColor = UIColor.clear.cgColor
        layer.strokeColor = color.cgColor
        layer.path = path.cgPath
        layer.cornerRadius = r
        layer.masksToBounds = true
        layer.strokeEnd = 0
        //        layer.lineCap = .butt
        return layer
    }
}
